package com.meila.cms.services.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

import com.meila.cms.dao.DesignPartMapper;
import com.meila.cms.dao.DictMapper;
import com.meila.cms.dao.MyPartsPropertyMapper;
import com.meila.cms.dao.MypartsLibMapper;
import com.meila.cms.dao.PartsDesignMapper;
import com.meila.cms.dao.PartsMapper;
import com.meila.cms.dao.PartsPropertyMapper;
import com.meila.cms.dto.AjaxObj;
import com.meila.cms.entity.Dict;
import com.meila.cms.entity.MyPartsProperty;
import com.meila.cms.entity.MypartsLib;
import com.meila.cms.entity.Parts;
import com.meila.cms.entity.PartsDesign;
import com.meila.cms.entity.User;

import com.meila.cms.model.MyPartsModel;
import com.meila.cms.model.MyPartsPropertyModel;
import com.meila.cms.model.PartsDesignModel;
import com.meila.cms.model.PartsModel;
import com.meila.cms.model.PartsPropertyModel;
import com.meila.cms.services.IPartDesignService;
import com.meila.cms.util.HtmlUtil;
import com.meila.cms.util.HttpUtils;
import com.meila.cms.util.ResourceLoader;
import com.meila.cms.util.StringUtil;
import com.meila.cms.util.ZipUtil;
import com.meila.cms.util.config.Property;
import com.meila.cms.util.page.PageBoundsUtil;
import com.meila.cms.util.page.Pager;
import com.meila.cms.util.page.SystemContext;
import com.meila.cms.util.pdf.PdfDocumentGenerator;
import com.meila.cms.web.CmsSessionContext;

@Service
public class PartDesignService extends BaseService implements
		IPartDesignService {

	private PartsMapper partsMapper;

	private MypartsLibMapper mypartsLibMapper;

	private DictMapper dictMapper;

	private PartsDesignMapper partsDesignMapper;

	private PartsPropertyMapper partsPropertyMapper;
	
	private MyPartsPropertyMapper myPartsPropertyMapper;
	
	private DesignPartMapper designPartMapper;

	public PartsMapper getPartsMapper() {
		return partsMapper;
	}

	@Inject
	public void setPartsMapper(PartsMapper partsMapper) {
		this.partsMapper = partsMapper;
	}

	public MypartsLibMapper getMypartsLibMapper() {
		return mypartsLibMapper;
	}

	@Inject
	public void setMypartsLibMapper(MypartsLibMapper mypartsLibMapper) {
		this.mypartsLibMapper = mypartsLibMapper;
	}

	public DictMapper getDictMapper() {
		return dictMapper;
	}

	@Inject
	public void setDictMapper(DictMapper dictMapper) {
		this.dictMapper = dictMapper;
	}

	public PartsDesignMapper getPartsDesignMapper() {
		return partsDesignMapper;
	}

	@Inject
	public void setPartsPropertyMapper(PartsPropertyMapper partsPropertyMapper) {
		this.partsPropertyMapper = partsPropertyMapper;
	}

	public PartsPropertyMapper getPartsPropertyMapper() {
		return partsPropertyMapper;
	}

	@Inject
	public void setPartsDesignMapper(PartsDesignMapper partsDesignMapper) {
		this.partsDesignMapper = partsDesignMapper;
	}
	
	public MyPartsPropertyMapper getMyPartsPropertyMapper() {
		return myPartsPropertyMapper;
	}

	@Inject
	public void setMyPartsDesignMapper(MyPartsPropertyMapper myPartsPropertyMapper) {
		this.myPartsPropertyMapper = myPartsPropertyMapper;
	}
	
	public DesignPartMapper getDesignPartMapper() {
		return designPartMapper;
	}

	@Inject
	public void setDesignPartMapper(DesignPartMapper designPartMapper) {
		this.designPartMapper = designPartMapper;
	}

	@Override
	public Pager<MyPartsModel> findMyParts(MyPartsModel myPartsModel) {
		// TODO Auto-generated method stub

		SystemContext.setPageSize(2);
		PageBounds pageBounds = PageBoundsUtil.PageBoundsOrderExtend("createTime.desc,updateTime.desc");	

		User user=getLoginUser();
		if (!StringUtil.isEmpty(user)) {
			myPartsModel.setUserid(user.getId());
		}
		
		int count = mypartsLibMapper.findMyPartsCount(myPartsModel, pageBounds);

		List<MyPartsModel> list = mypartsLibMapper.findMyParts(myPartsModel,pageBounds);

		Pager<MyPartsModel> pages = new Pager<MyPartsModel>(count, list);

		return pages;
	}

	@Override
	public void partDesignToAddEdit(PartsDesignModel partsDesignModel,
			Model model) {
		// TODO Auto-generated method stub
		// 零件类型
		Dict dict = new Dict();
		dict.setCategory("PartType");
		List<Dict> partTypeList = dictMapper.selectSelective(dict);
		model.addAttribute("partTypeList", partTypeList);

		// 备选零件
		model.addAttribute("partList", getPartList(partsDesignModel));
		
		// 零件属性列表
		model.addAttribute("propertyList", getPropertyList(partsDesignModel));

		// 新增
		if (StringUtil.isEmpty(partsDesignModel.getId())) {
			
		} else {
			// 修改
			partsDesignModel = partsDesignMapper
					.selectByPrimaryKey(partsDesignModel.getId());
		}

		if (StringUtil.isEmpty(partsDesignModel.getPartsType())) {
			partsDesignModel.setPartsType(1);
		} else {
			partsDesignModel.setPartsType(partsDesignModel.getPartsType());
		}

		partsDesignModel.setPartstypeName(dictUtil.getNameByValue("PartType",
				partsDesignModel.getPartsType().toString()));
		model.addAttribute("partsDesignModel", partsDesignModel);
	}

	@Override
	public List getPartList(PartsDesignModel partsDesignModel) {
		// TODO Auto-generated method stub
		PartsModel partsModel = new PartsModel();
		if (StringUtil.isEmpty(partsDesignModel.getPartsType())) {
			partsModel.setPartsType(1);
		} else {
			partsModel.setPartsType(partsDesignModel.getPartsType());
		}
		partsModel.setCarid(partsDesignModel.getCarid());
		partsModel.setPartsName(partsDesignModel.getPartsName());

		List<PartsModel> partsList = partsMapper.selectSelective(partsModel);
		return partsList;
	}

	@Override
	public List getPropertyList(PartsDesignModel partsDesignModel) {
		// TODO Auto-generated method stub
		PartsPropertyModel propertyModel = new PartsPropertyModel();
		if (StringUtil.isEmpty(partsDesignModel.getId())) {
			return null;
			//propertyModel.setPartsid(1);
		} else {
			propertyModel.setPartsid(partsDesignModel.getId());
		}

		List<PartsPropertyModel> partsPropertyList = partsPropertyMapper.selectProperty(propertyModel.getPartsid());
		return partsPropertyList;
	}

	//我的零件库下载
	@Override
	public ResponseEntity<byte[]> downloadFileBychose(String designid,
			Integer[] chose, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		MypartsLib mypartsLib=mypartsLibMapper.selectByPrimaryKey(Integer.valueOf(designid));
		
		HttpHeaders headers = new HttpHeaders();    
	    File file;
	    ResponseEntity<byte[]> result = null;
	    
	    String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String template_path;
        // classpath 路径
    	String  outputFileClass = ResourceLoader.getPath("");
       	long    timp;
       	String   outputFile = null;
 
       	
		String filenames[]=new String[chose.length];
		File[] files =new File[chose.length];
        try {
				for (int i = 0; i < chose.length; i++) {
					
					if((mypartsLib.getTwoDid()==null & chose[i]==0)){
						continue;
					}
					
					outputFile = new File(outputFileClass).getParentFile().getParent();
					timp = System.currentTimeMillis();
					
					switch ( chose[i]) {
					case 1:
					        filenames[i]="2D文档.pdf";
						    outputFile =outputFile+"\\resources\\download\\"+timp+".pdf";
							//先下载到服务器目录
						    HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+mypartsLib.getTwoDid());
			
					    	break;
					case 2:
					        filenames[i]="3D文档.pdf";
						    outputFile = outputFile+"\\resources\\download\\"+timp+".pdf";
							//先下载到服务器目录
						    HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+mypartsLib.getThreeDid());
					    	break;
					case 3:
						 filenames[i]="编程图.stp";
						 outputFile = outputFile+"\\resources\\download\\"+timp+".stp";
						 //先生成到服务器目录
						 HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+mypartsLib.getProgrammeid());
						 break;
					case 4:
						 filenames[i]="产品制作图.stp";
						 outputFile = outputFile+"\\resources\\download\\"+timp+".stp";
						 //先生成到服务器目录
						 HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+mypartsLib.getProductid());
						 break;
					case 5:
						 filenames[i]="模具图.stp";
						 outputFile = outputFile+"\\resources\\download\\"+timp+".stp";
						 //先生成到服务器目录
						 HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+mypartsLib.getModleid());
					default:
						break;
					}
					
			        //记录下载到服务器的目录
				    files[i] = new File(outputFile);
				}
		
				//打包下载到服务器目录
				timp = System.currentTimeMillis();
				outputFile =  new File(outputFileClass).getParentFile().getParent()+"\\resources\\download\\"+mypartsLib.getPartsName()+"_"+timp+".zip";
				ZipUtil.compressFilesToZip(files, outputFile, filenames);
				
				//设置响应头，控制浏览器下载该文件
				file = new File(outputFile);  
		        String fileName=new String((mypartsLib.getPartsName()+"_"+timp+".zip").getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
		        headers.setContentDispositionFormData("attachment", fileName); 
		        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
		        result = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
		                headers, HttpStatus.CREATED);
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public AjaxObj updatePartDesign(PartsDesignModel partsDesignModel) {
		// TODO Auto-generated method stub
		AjaxObj ajaxObj=new AjaxObj();
		
		try{
			partsDesignModel.setUpdateTime(new Date());
			User user=getLoginUser();
			
			Parts parts=partsMapper.selectByPrimaryKey(partsDesignModel.getId());
			parts.setPartsNo(partsDesignModel.getPartsNo());
			parts.setPartsName(partsDesignModel.getPartsName());
			parts.setMaterial(partsDesignModel.getMaterial());
			parts.setComment(partsDesignModel.getComment());
			if(!StringUtil.isEmpty(user)){
				parts.setModifier(user.getId());
			}
			parts.setUpdateTime(new Date());
			//更新零件的参数
			partsMapper.updateByPrimaryKey(parts);
			
			List<PartsPropertyModel> list=partsPropertyMapper.selectProperty(partsDesignModel.getId());
			//更新property
			if(!list.isEmpty()){
				for(int i=0;i<list.size();i++){
					list.get(i).setPropertyValue(partsDesignModel.getPropertyValue()[i]);
					partsPropertyMapper.updateByPrimaryKey(list.get(i));
				}
			}
			ajaxObj.setResult(true);
			ajaxObj.setMsg("操作成功");
			
		}catch(Exception e){
			// TODO: handle exception
			ajaxObj.setResult(false);
			ajaxObj.setMsg("操作失败");
			e.printStackTrace();
		}
		return ajaxObj;
	}

	@Override
	public AjaxObj addPartDesign(MyPartsModel myPartsModel) {
		// TODO Auto-generated method stub
		AjaxObj ajaxObj=new AjaxObj();
		
		try{
			User user=getLoginUser();
			PartsDesign partsDesign=new PartsDesign();
			if (!StringUtil.isEmpty(user)){
				partsDesign.setUserid(user.getId());
			}
			partsDesign.setDesigname(myPartsModel.getDesigname());
			partsDesign.setCreateTime(new Date());
			partsDesign.setUpdateTime(new Date());
			partsDesign.setDel(0);
			//向t_parts_design插入数据
			designPartMapper.insert(partsDesign);
			
			//向t_myparts_lib插入数据
			List<PartsDesignModel> list=partsDesignMapper.selectParts();
			//获取designid
			int designid=designPartMapper.selectMaxid();
			if(!list.isEmpty()){
				for(int i=0;i<list.size();i++){
					MypartsLib mypartsLib=new MypartsLib();
					mypartsLib.setPartsNo(list.get(i).getPartsNo());
					mypartsLib.setPartsName(list.get(i).getPartsName());
					mypartsLib.setMaterial(list.get(i).getMaterial());
					mypartsLib.setComment(list.get(i).getComment());
					mypartsLib.setCreateTime(new Date());
					mypartsLib.setUpdateTime(new Date());
					mypartsLib.setTwoDid(list.get(i).getTwoDid());
					mypartsLib.setThreeDid(list.get(i).getThreeDid());
					mypartsLib.setProgrammeid(list.get(i).getProgrammeid());
					mypartsLib.setProductid(list.get(i).getProductid());
					mypartsLib.setModleid(list.get(i).getModleid());
					mypartsLib.setDel(list.get(i).getDel());
					mypartsLib.setCarid(list.get(i).getCarid());
					mypartsLib.setPartsType(list.get(i).getPartsType());
					mypartsLib.setUserid(user.getId());
					mypartsLib.setDesignid(designid);
					mypartsLibMapper.insert(mypartsLib);
				}
			}
			//向t_myparts_property插入数据
			List<PartsPropertyModel> list1=partsPropertyMapper.selectPropertyList();
			if(!list1.isEmpty()){
				int flag=list1.get(0).getPartsid();
				for(int i=0;i<list1.size();i++){
					MyPartsPropertyModel myPartsPropertyModel=new MyPartsPropertyModel();
					myPartsPropertyModel.setPropertyName(list1.get(i).getPropertyName());
					myPartsPropertyModel.setPropertyValue(list1.get(i).getPropertyValue());
					myPartsPropertyModel.setDel(list1.get(i).getDel());
					myPartsPropertyModel.setPartsid(mypartsLibMapper.selectByDesignid(designid)+list1.get(i).getPartsid()-flag);
					myPartsPropertyMapper.insert(myPartsPropertyModel);
				}
			}
			ajaxObj.setResult(true);
			
		}catch(Exception e){
			ajaxObj.setResult(false);
			ajaxObj.setMsg("操作失败");
			e.printStackTrace();
		}
		return ajaxObj;
	}

	@Override
	public void partDesignToAdd(MyPartsModel myPartsModel, Model model) {
		// TODO Auto-generated method stub
		// 零件类型
		Dict dict = new Dict();
		dict.setCategory("PartType");
		List<Dict> partTypeList = dictMapper.selectSelective(dict);
		model.addAttribute("partTypeList", partTypeList);
		
		// 我的备选零件
		model.addAttribute("myPartList", getMyPartList(myPartsModel));
		
		// 我的零件属性列表
		model.addAttribute("myPartsPropertyList", getMyPropertyList(myPartsModel));
		
		if(StringUtil.isEmpty(myPartsModel.getId())){
			
		}else{
			//修改
			myPartsModel=mypartsLibMapper.selectById(myPartsModel.getId());
		}
		
		if(StringUtil.isEmpty(myPartsModel.getPartsType())){
			myPartsModel.setPartsType(1);
		}else{
			myPartsModel.setPartsType(myPartsModel.getPartsType());
		}
		
		myPartsModel.setPartstypeName(dictUtil.getNameByValue("PartType", 
				myPartsModel.getPartsType().toString()));
		model.addAttribute("myPartsModel", myPartsModel);
	}

	public List getMyPropertyList(MyPartsModel myPartsModel) {
		// TODO Auto-generated method stub
		MyPartsPropertyModel myPartsPropertyModel=new MyPartsPropertyModel();
		
		if(StringUtil.isEmpty(myPartsModel.getId())){
			return null;
		}else{
			List<MyPartsProperty> myPropertyList = myPartsPropertyMapper.selectProperty(myPartsModel.getId());
			return myPropertyList;
		}		
		
	}	

	@Override
	public List getMyPartList(MyPartsModel myPartsModel) {
		// TODO Auto-generated method stub
		MypartsLib mypartsLib=new MypartsLib();
		User user=getLoginUser();
		mypartsLib.setUserid(user.getId());
		if (StringUtil.isEmpty(myPartsModel.getPartsType())) {
			mypartsLib.setPartsType(1);
		} else {
			mypartsLib.setPartsType(myPartsModel.getPartsType());
		}
		List<MypartsLib> mypartsList = mypartsLibMapper.selectSelective(mypartsLib);
		return mypartsList;
	}

	@Override
	public AjaxObj updateMyPartDesign(MyPartsModel myPartsModel) {
		// TODO Auto-generated method stub
		AjaxObj ajaxObj=new AjaxObj();
		
		try{
			myPartsModel.setUpdateTime(new Date());
			
			MypartsLib mypartsLib=mypartsLibMapper.selectByPrimaryKey(myPartsModel.getId());
			mypartsLib.setPartsNo(myPartsModel.getPartsNo());
			mypartsLib.setPartsName(myPartsModel.getPartsName());
			mypartsLib.setMaterial(myPartsModel.getMaterial());
			mypartsLib.setComment(myPartsModel.getComment());
			mypartsLib.setProgrammeid(myPartsModel.getProgrammeid());
			mypartsLib.setProductid(myPartsModel.getProductid());
			mypartsLib.setModleid(myPartsModel.getModleid());
			mypartsLib.setUpdateTime(new Date());
			//更新我的零件库的参数
			mypartsLibMapper.updateByPrimaryKey(mypartsLib);
			
			List<MyPartsProperty> list=myPartsPropertyMapper.selectProperty(myPartsModel.getId());
			//更新我的零件库property
			if(!list.isEmpty()){
				for(int i=0;i<list.size();i++){
					list.get(i).setPropertyValue(myPartsModel.getPropertyValue()[i]);
					myPartsPropertyMapper.updateByPrimaryKey(list.get(i));
				}
			}
			ajaxObj.setResult(true);
			ajaxObj.setMsg("操作成功");
			
		}catch(Exception e){
			// TODO: handle exception
			ajaxObj.setResult(false);
			ajaxObj.setMsg("操作失败");
			e.printStackTrace();
		}
		return ajaxObj;
	}

	@Override
	public AjaxObj update(MypartsLib mypartsLib) {
		// TODO Auto-generated method stub
		AjaxObj  ajaxObj=new AjaxObj();
		
		try{
			MypartsLib myparts=mypartsLibMapper.selectByPrimaryKey(mypartsLib.getId());
			myparts.setUpdateTime(new Date());
			myparts.setProgrammeid(mypartsLib.getProgrammeid());
			myparts.setProductid(mypartsLib.getProductid());
			myparts.setModleid(mypartsLib.getModleid());
			mypartsLibMapper.updateByPrimaryKeySelective(myparts);
			ajaxObj.setResult(true);
			ajaxObj.setMsg("操作成功");
		}catch(Exception e){
			// TODO: handle exception
			ajaxObj.setResult(false);
			ajaxObj.setMsg("操作失败");
			e.printStackTrace();
		}
		
		return ajaxObj;
	}

	@Override
	public ResponseEntity<byte[]> dowloadFileBychoseFromParts(String designid,
			Integer[] chose, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		Parts parts=partsMapper.selectByPrimaryKey(Integer.valueOf(designid));
		
		HttpHeaders headers = new HttpHeaders();    
	    File file;
	    ResponseEntity<byte[]> result = null;
	    
	    String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String template_path;
        // classpath 路径
    	String  outputFileClass = ResourceLoader.getPath("");
       	long    timp;
       	String   outputFile = null;
 
       	
		String filenames[]=new String[chose.length];
		File[] files =new File[chose.length];
		try{
			for (int i = 0; i < chose.length; i++){
				
				if((parts.getTwoDid()==null & chose[i]==0)){
					continue;
				}
				
				outputFile = new File(outputFileClass).getParentFile().getParent();
				timp = System.currentTimeMillis();
				
				switch ( chose[i]){
				case 1:
			        filenames[i]="2D文档.pdf";
				    outputFile =outputFile+"\\resources\\download\\"+timp+".pdf";
					//先下载到服务器目录
				    HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+parts.getTwoDid());
	
			    	break;
				case 2:
			        filenames[i]="3D文档.pdf";
				    outputFile = outputFile+"\\resources\\download\\"+timp+".pdf";
					//先下载到服务器目录
				    HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+parts.getThreeDid());
			    	break;
				case 3:
					filenames[i]="编程图.stp";
					outputFile = outputFile+"\\resources\\download\\"+timp+".stp";
					//先生成到服务器目录
					HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+parts.getProgrammeid());
					break;
				case 4:
					filenames[i]="产品制作图.stp";
					outputFile = outputFile+"\\resources\\download\\"+timp+".stp";
					//先生成到服务器目录
					HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+parts.getProductid());
					break;
				case 5:
					filenames[i]="模具图.stp";
					outputFile = outputFile+"\\resources\\download\\"+timp+".stp";
					//先生成到服务器目录
					HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+parts.getModleid());
				default:
					break;
				}
				
				//记录下载到服务器的目录
			    files[i] = new File(outputFile);
			}
			
			//打包下载到服务器目录
			timp = System.currentTimeMillis();
			outputFile =  new File(outputFileClass).getParentFile().getParent()+"\\resources\\download\\"+parts.getPartsName()+"_"+timp+".zip";
			ZipUtil.compressFilesToZip(files, outputFile, filenames);
			
			//设置响应头，控制浏览器下载该文件
			file = new File(outputFile);  
	        String fileName=new String((parts.getPartsName()+"_"+timp+".zip").getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
	        headers.setContentDispositionFormData("attachment", fileName); 
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
	        result = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
	                headers, HttpStatus.CREATED);
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}